package servlet;

import com.alibaba.fastjson.JSON;
import service.UserService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

@WebServlet(name = "UserServlet", value = "/user")
public class UserServlet extends HttpServlet {

    UserServlet userServlet=new UserServlet();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//判断使用功能：1.检查用户名是否存在
        //2.注册用户（method:registerUser）
        String method = request.getParameter("method");
        switch (method){
            case "checkUsername":
                checkUsername(request,response);
                break;
                case "registerUser":
                    break;
        }
    }

    private void registerUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //result
        String username = request.getParameter("username");
        boolean b = UserService.checkUsername(username);
        //b-----true 存在 false 不存在
        HashMap<String,String> map=new HashMap<>();
        if (b){
            //USERNAME_EXIST  用户名已存在
            map.put("result","USERNAME_EXIST");
        }else {
            // USERNAME_CAN_USE  用户名能使用
            map.put("result","USERNAME_CAN_USE");
        }
        String r= JSON.toJSONString(map);
//        text/html;charset=utf-8
         response.setContentType("application/json");
        PrintWriter out = response.getWriter();
        out.write(r);
    }

    private void checkUsername(HttpServletRequest request, HttpServletResponse response) {

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }
}
